/* ========================================================================== */
/*   Beeper.cpp                                                               */
/*   (c) 2012 Team 7 Hogeschool Utrecht ICT TI                                */
/*		Lars Stolwijk, Gerben Boot, Guido van Hienen, Marcel Boelen			  */
/*                                                                            */
/*   Generates instructed sounds by switching the beeper on and off           */
/* ========================================================================== */

#include "Beeper.h"

armboard::output_pin & speaker = armboard::chip::pin_0_8; 
armboard::output_pin & jackOutput = armboard::chip::pin_0_25; 

void Beeper::main()
{
	CurrentState = WAITING;
	SoundEvent s;
	speaker.direction_set_output();
	jackOutput.direction_set_output();
	int i = 0;
	char soundChannelCount = 0;
	while(true)
	{
		if(CurrentState == WAITING)
		{
			if(soundChannelCount == 0)
			{
				RTOS::event e = wait( SoundChannel);
				if( SoundChannel == e)
				{
					s = SoundChannel.read();
					BTTimer.set(s.time MS);
					CurrentState = PLAYINGSOUND;
				}
			}
			else
			{
				s = SoundChannel.read();
				BTTimer.set(s.time MS);
				CurrentState = PLAYINGSOUND;
				soundChannelCount--;
			}
		}
		else if(CurrentState == PLAYINGSOUND)
		{
			RTOS::event e = wait( );
			if(BTClock == e)
			{
	   			if(i>=(4000/(s.freq*2)))
				{//calculation to see how many clock signals can be skipt
				   SwitchBeepBit();
				   i=0;
				} 
				else
				{
					i++;
				}
				
			} else if(BTTimer == e)
			{
				CurrentState = WAITING;
			}
			else if( SoundChannel == e)
			{
				soundChannelCount++;
			}
		}
	}
}

void Beeper::SwitchBeepBit()
{
   	if(speakerOn == true)
	   {
		speaker.set( 1 );
		jackOutput.set( 1 );
		speakerOn = false;
	} else
	{
	    speaker.set( 0 );
	    jackOutput.set( 0 );
	    speakerOn = true;
	}
}

void Beeper::PlaySound(int freq, int time)
{
	SoundEvent * s = new SoundEvent(freq, time);
	SoundChannel.write(*s);
}

